package com.lyq.dao;

import com.lyq.bean.Student;
import com.lyq.utils.DBMySql;

import java.util.ArrayList;
import java.util.List;


public class StudentDao {

    /**
     * 添加学生
     * @param student 学生对象
     * @return 添加结果
     */
    public static int addStudent(Student student) {
        String sql = "insert into student (stu_id,name,sex,grade,cohort)values(?,?,?,?,?)";
        return DBMySql.update(sql,student.getStu_id(),student.getName(),student.getSex(),student.getGrade(),student.getCohort());
    }

    /**
     * 查询学生
     * @param currentPage 当前页数
     * @param pageSize 每页数量
     * @param params sql参数
     * @return 返回查询到的数据
     */
    public static List<Student> getStudent(int currentPage, int pageSize,String... params) {
        // 基础 SQL
        String sql = "SELECT * FROM student WHERE 1=1";
        List<String> conditions = new ArrayList<>();
        List<Object> values = new ArrayList<>();

        // 按顺序解析参数
        if (params.length >= 5) {
            String studentID = params[0];
            String name = params[1];
            String sex = params[2];
            String grade = params[3];
            String cohort = params[4];

            if (studentID != null && !studentID.trim().isEmpty()) {
                conditions.add("stu_id LIKE ?");
                values.add("%" + studentID.trim() + "%");
            }
            if (name != null && !name.trim().isEmpty()) {
                conditions.add("name LIKE ?");
                values.add("%" + name.trim() + "%");
            }
            if (sex != null && !sex.trim().isEmpty()) {
                conditions.add("sex = ?");
                values.add(sex);
            }
            if (grade != null && !grade.trim().isEmpty()) {
                conditions.add("grade LIKE ?");
                values.add("%" + grade.trim() + "%");
            }
            if (cohort != null && !cohort.trim().isEmpty()) {
                conditions.add("cohort LIKE ?");
                values.add("%" + cohort.trim() + "%");
            }
        }

        // 拼接条件
        if (!conditions.isEmpty()) {
            sql += " AND " + String.join(" AND ", conditions);
        }

        int offset = (currentPage - 1) * pageSize;

        // 添加分页
        sql += " LIMIT ? OFFSET ?";
        values.add(pageSize);
        values.add(offset);

        // 调用 DBMySql.queryAll，传入 SQL 和参数
        return DBMySql.queryAll(sql, Student.class, values.toArray());
    }

    public static int deleteStudent(String stuID){
        String sql = "delete from student where stu_id=?";
        return DBMySql.update(sql,stuID);
    }

    public static int updateStudent(Student student){
        String sql = "update student set name=?,sex=?,grade=?,cohort=? where stu_id=?";
        return DBMySql.update(sql,student.getName(),student.getSex(),student.getGrade(),student.getCohort(),student.getStu_id());
    }


}
